package cn.com.surker.system.service.impl;

import cn.com.surker.common.Code;
import cn.com.surker.enums.StateEnum;
import cn.com.surker.redis.RedisUtils;
import cn.com.surker.system.dao.DataSourceInfoDao;
import cn.com.surker.system.entity.DataSourceInfo;
import cn.com.surker.system.service.DataSourceService;
import cn.com.surker.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author lucky
 * @create 2022年06月27 16:44
 * @desc
 */
@Service
public class DataSourceServiceImpl implements DataSourceService {

    @Resource
    private DataSourceInfoDao dsDao;
    /**微信收料数据源**/
    @Autowired
    @Qualifier("sqlServerJdbcTemplate")
    private JdbcTemplate dateCenterJdbcTemplate;

    /**redis工具类**/
    @Resource
    private RedisUtils redisUtils;

    /**
     * 查询已开通微信上号系统的数据源
     * @return
     */
    @Cacheable(cacheNames = "gpsByOriginId")
    public List<DataSourceInfo> queryRelationGps() {
        return dsDao.queryRelationGps();
    }


    /**
     * 根据公司ID查询数据源信息
     * @param orgId
     * @return
     */
    @Cacheable(cacheNames = "gpsByOriginId", key = "#orgId")
    public DataSourceInfo getDataSourceByOrgId(Long orgId) {
        if (StringUtils.isNull(orgId))
            return null;

        DataSourceInfo ds = dsDao.queryDSByOriginId(orgId);
        return ds;
    }

	@Override
	public DataSourceInfo getDataSourceByOrgIdV1(Long orgId, Integer type) {
		return null;
	}


	/**
     * 根据ID查询数据源
     * @param id
     * @return
     */
    @Cacheable(cacheNames = "gpsByOriginId", key = "#id")
    public DataSourceInfo getById(Long id) {
        if (StringUtils.isNull(id))
            return null;

        DataSourceInfo ds = dsDao.selectById(id);
        return ds;
    }

    @Override
    public Map<String, Object> cloudWaring() {
        return null;
    }


    /**
     * 根据用户ID查询关联数据库
     * @param uid
     * @return
     */
    public List<DataSourceInfo> findByUidRelation(Long uid, Integer type) {
        if (StringUtils.isNull(uid))
            return null;
        return dsDao.queryByUidRelation(uid, type);
    }
    /**
     * 根据条件查询所有的数据
     * @param dto
     * @return
     */
    @Cacheable(cacheNames = "queryDatasourceInfo")
    public List<DataSourceInfo> findAll(DataSourceInfo dto) {
        QueryWrapper<DataSourceInfo> query = new QueryWrapper();
        query.setEntity(dto);
        List<DataSourceInfo> list = dsDao.selectList(query);

        return list;
    }

    /**
     * 分页查询数据
     * @param dto
     * @return
     */
    public IPage findAllByPage(DataSourceInfo dto, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        QueryWrapper<DataSourceInfo> query = new QueryWrapper();
        if (dto != null && !StringUtils.isNull(dto.getName()))
            query.like("name", dto.getName());
        if (dto != null && !StringUtils.isNull(dto.getType()))
            query.eq("type", dto.getType());
        if (dto != null && !StringUtils.isNull(dto.getStatus()))
            query.eq("status", dto.getStatus());

        IPage<DataSourceInfo> iPage = dsDao.selectPage(new Page<>((offset + limit) /limit, limit), query);
        /**分页插件**/
        if (!StringUtils.isNull(iPage.getRecords())) {
            PageInfo pageInfo = new PageInfo(iPage.getRecords());
            if (!StringUtils.isNull(pageInfo.getTotal()))
                iPage.setTotal(pageInfo.getTotal());
        }
        return iPage;
    }

    /**
     * 新增数据
     *
     * @param dto page
     * @return
     */
    @CacheEvict(value = "gpsByOriginId", allEntries = true)
    public Integer saveInit(DataSourceInfo dto) {
        if (StringUtils.isAllParamNull(dto.getType(), dto.getCode(), dto.getDriver(),
                dto.getName(), dto.getPassword(), dto.getUsername(), dto.getUrl()))
            return Code.PARAM_ERROR.getCode();
        dto.setStatus(StateEnum.ENABLED.getCode());
        dto.setCreateTime(new Date());
        int saveStatus = dsDao.insert(dto);
        if (saveStatus > 0)
            return 0;
        else
            return -1;

    }

    /**
     * 更新数据状态
     *
     * @param status 状态(0:启用，1:禁用)
     * @param id     标识
     * @return
     */
    @CacheEvict(value = "gpsByOriginId", allEntries = true)
    public Integer updateStatus(Long id, Integer status) {
        if (StringUtils.isAllParamNull(id, status))
            return Code.PARAM_ERROR.getCode();

        DataSourceInfo info = new DataSourceInfo();
        info.setId(id);
        info.setStatus(status);

        Integer code = dsDao.updateById(info);
        if (code > 0)
            return 0;
        else
            return -1;
    }

    /**
     * 更新数据
     *
     * @param dto page
     * @return
     */
    @CacheEvict(value = "gpsByOriginId", allEntries = true)
    public Integer update(DataSourceInfo dto) {
        if (dto == null || StringUtils.isNull(dto.getId()))
            return Code.PARAM_ERROR.getCode();

        int saveStatus = dsDao.updateById(dto);
        if (saveStatus > 0)
            return 0;
        else
            return -1;
    }
    /**
     * 根据名称查询数据源
     * @param orgName
     * @return
     */
    public DataSourceInfo findByName(String orgName) {
        if (StringUtils.isNull(orgName))
            return null;
        QueryWrapper<DataSourceInfo> query = new QueryWrapper<>();
        query.eq("name", orgName);
        query.eq("status", 0);
        query.eq("biz_type", 1);
        List<DataSourceInfo> list = dsDao.selectList(query);
        if (list == null || list.size() == 0)
            return null;
        return list.get(0);
    }

    /**
     * 根据名称查询数据源
     * @param code
     * @return
     */
    public DataSourceInfo findByCode(String code) {
        QueryWrapper<DataSourceInfo> query = new QueryWrapper<>();
        query.eq("code", code);
        query.eq("status", 0);
        query.eq("biz_type", 1);
        List<DataSourceInfo> list = dsDao.selectList(query);
        if (list == null || list.size() == 0)
            return null;
        return list.get(0);
    }
}
